<template>
    <div>
        <el-upload
                :action="uploadAction"
                class="upload-demo"
                accept="image/jpg,image/png"
                drag
                :on-preview="handlePictureCardPreview"
                :on-error="handleUploadError"
                :on-success="handleUploadSuccess"
                name="up_file"
                list-type="picture"
                :file-list="fileList"
                :data="{type:'image'}"
                :on-remove="handleRemove"
                :headers="uploadHeader">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
        <el-dialog v-model="dialogVisible" size="small">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>

</template>
<script>
    import { mapGetters } from 'vuex'
    import _ from 'lodash'
    import params from '../../conf/params'
    export default {
      props: {
        fileList: {
          type: Array,
          default () {
            return []
          }
        },
        isUploadToTemp: {
          type: Boolean,
          default: true
        }
      },
      data () {
        return {
          dialogVisible: false,
          dialogImageUrl: ''
        }
      },
      computed: {
        ...mapGetters([
          'token'
        ]),
        uploadAction () {
          let action = `${params.base_url}/file/upload`
          if (!this.isUploadToTemp) {
            action = `${params.base_url}/file/attachment/upload`
          }
          return action
        },
        uploadHeader () {
          return {
            Authorization: `Bearer ${this.token}`,
            Accept: 'application/json'
          }
        }
      },
      methods: {
        handlePictureCardPreview (file) {
          this.dialogImageUrl = file.url
          this.dialogVisible = true
        },
        handleUploadError () {
          this.$message.error('文件上传失败')
        },
        handleUploadSuccess (response, file, fileList) {
          _.remove(fileList, obj => {
            return obj.uid !== file.uid
          })
          this.$emit('upload-success', response)
        },
        handleRemove (file) {
          this.$emit('remove-file', file.response)
        }
      }
    }
</script>
<style scoped>

</style>